package com.bluesky.webflux.oa.service;

import com.bluesky.webflux.oa.model.OaUser;
import com.bluesky.webflux.oa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Mono<OaUser> addUser(OaUser user) {
        return userRepository.save(user);
    }

    public Mono<ResponseEntity<Void>> delUser(String id) {
        return userRepository.findById(id)
                .flatMap(user -> userRepository.delete(user).then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK))))
                .defaultIfEmpty(new ResponseEntity<Void>(HttpStatus.NOT_FOUND));
    }

    public Mono<ResponseEntity<OaUser>> updateUser(OaUser user) {
        return userRepository.findById(user.getId())
                .flatMap(user0 -> userRepository.save(user))
                .map(user0 -> new ResponseEntity<OaUser>(user0, HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<OaUser>(HttpStatus.NOT_FOUND));
    }

    public Flux<OaUser> getAllUser() {
        return userRepository.findAll();
    }

}
